//
//  PetController.swift
//  
//
//  Created by Jiang Chencheng on 2024/9/12.
//

import Vapor
import Fluent

struct PetController: RouteCollection {
    func boot(routes: any Vapor.RoutesBuilder) throws {
        
        let diary = routes
            .grouped("pet")
            .grouped(SessionToken.authenticator(), SessionToken.guardMiddleware())
        
        // tap your pet
        diary.post("tap", use: tapPet)
        
        // play with your pet
        diary.post("play", use: playWithPet)
    }
}

extension PetController {
    
    
    @Sendable
    func tapPet(req: Request) async throws -> BizResponse<RewardResp> {
        let userID = try req.getAuthedUserID()
        
        let myRoom = try await Room.query(on: req.db, userID: userID)
        
        try await req.db.transaction {
            try await Event.log(on: $0, roomID: myRoom.requireID(), userID: userID, action: .tapPet, comment: "tap pet reward 20 stars")
            myRoom.star += 20
            try await myRoom.save(on: $0)
        }
        
        let reward = RewardResp.Reward(value: 20, type: .star)
        let resp = RewardResp(reward: reward, room: myRoom.toDTO())
        return BizResponse(data: resp)
    }
    
    @Sendable
    func playWithPet(req: Request) async throws -> BizResponse<RewardResp> {

        let userID = try req.getAuthedUserID()
        
        let myRoom = try await Room.query(on: req.db, userID: userID)
        
        try await req.db.transaction {
            try await Event.log(on: $0, roomID: myRoom.requireID(), userID: userID, action: .playWithPet, comment: "play with pet reward 20 stars")
            myRoom.star += 20
            try await myRoom.save(on: $0)
        }
        
        let reward = RewardResp.Reward(value: 20, type: .star)
        let resp = RewardResp(reward: reward, room: myRoom.toDTO())
        return BizResponse(data: resp)
    }
    
}
